package com.uy.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uy.system.common.constant.SystemConstants;
import com.uy.system.common.utils.SessionUtils;
import com.uy.system.exception.ErrorCode;
import com.uy.system.exception.SystemException;
import com.uy.system.id.SnowFlakeFactory;
import com.uy.system.model.dto.SysUserDTO;
import com.uy.system.model.entity.SysUser;
import com.uy.system.model.entity.SysUserRole;
import com.uy.system.model.form.SysUserFrom;
import com.uy.system.model.vo.SysUserVo;
import com.uy.system.mapper.SysUserMapper;
import com.uy.system.service.ISysUserRoleService;
import com.uy.system.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uy.system.utils.EncryptionUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author ly
 * @since 2024-03-22
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Resource
    private ISysUserRoleService iSysUserRoleService;

    @Override
    public List<SysUserVo> getSysUserList() {
        return baseMapper.getSysUserList();
    }

    @Override
    public Page<SysUser> querySysUser(SysUserDTO dto) {
        Page<SysUser> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(dto.getNickName())){
            lqw.eq(SysUser::getNickName, dto.getNickName());
        }
        if (StrUtil.isNotBlank(dto.getPhonenumber())){
            lqw.eq(SysUser::getPhonenumber, dto.getPhonenumber());
        }
        if (dto.getStatus() != null){
            lqw.eq(SysUser::getStatus, dto.getStatus());
        }
        lqw.eq(SysUser::getDelFlag, "0");
        return baseMapper.selectPage(page, lqw);
    }

    @Override
    public SysUser findSysUser(String username, String password) {
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysUser::getUserName, username).eq(SysUser::getPassword, password);
        return baseMapper.selectOne(lqw);
    }

    @Override
    public SysUser findSysUserByUserId(Long userId) {
        if (userId == null) return null;
        return baseMapper.selectById(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrEditSysUser(SysUserFrom from) {
        if (from == null){
            throw new SystemException(ErrorCode.PARAMS_INVALID);
        }
        SysUser sysUser = buildSysUser(from);
        SysUserRole role = new SysUserRole();
        role.setRoleId(from.getRoleId());
        role.setUserId(sysUser.getUserId());
        if (from.getUserId() == null){
            baseMapper.insert(sysUser);
        }else {
            baseMapper.updateById(sysUser);
            iSysUserRoleService.delSysUserRoleByUserId(sysUser.getUserId());
        }
        iSysUserRoleService.insertSysUserRole(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delSysUserByUserId(Long userId) {
        if (userId == null){
            throw new SystemException(ErrorCode.PARAMS_INVALID);
        }
        SysUser sysUser = SessionUtils.getSysUser();
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setDelFlag(SystemConstants.DEL_FLAG_2);
        user.setUpdateBy(sysUser.getUserId());
        user.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(user);
        iSysUserRoleService.delSysUserRoleByUserId(userId);
    }

    @Override
    public SysUserVo getSysUserInfo(Long userId) {
        if (userId == null){
            throw new SystemException(ErrorCode.PARAMS_INVALID);
        }
        return baseMapper.getSysUserInfo(userId);
    }

    /**
     * 构建SysUser对象
     * @param from 入参
     */
    private SysUser buildSysUser(SysUserFrom from){
        SysUser sysUser = SessionUtils.getSysUser();
        SysUser user = new SysUser();
        user.setUserName(from.getUsername());
        user.setNickName(from.getNickname());
        user.setStatus(StrUtil.toString(from.getStatus()));
        user.setSex(StrUtil.toString(from.getSex()));
        user.setDeptId(from.getDeptId());
        user.setPhonenumber(from.getPhonenumber());
        if (from.getUserId() == null){
            user.setUserId(SnowFlakeFactory.getSnowFlakeFromCache().nextId());
            user.setPassword(initPassword(from.getUsername()));
            user.setUserType(SystemConstants.USER_TYPE);
            user.setCreateTime(LocalDateTime.now());
            user.setCreateBy(sysUser.getUserId());
            user.setCreateDept(sysUser.getCreateDept());
            user.setStatus(SystemConstants.DEL_FLAG_0);
        }else {
            user.setUserId(from.getUserId());
            user.setUpdateBy(sysUser.getUserId());
            user.setUpdateTime(LocalDateTime.now());
        }
        return user;
    }

    /**
     * 密码初始化
     */
    private String initPassword(String password){
        return EncryptionUtil.encryptAES(password);
    }
}
